package cn.hackcloud.netty.basic.aio;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;

public class ReadCompletionHandler implements CompletionHandler<Integer, ByteBuffer> {
	private AsynchronousSocketChannel asynchronousSocketChannel;

	public ReadCompletionHandler(AsynchronousSocketChannel asynchronousSocketChannel) {
		super();
		if (this.asynchronousSocketChannel == null) {
			this.asynchronousSocketChannel = asynchronousSocketChannel;
		}
	}

	@Override
	public void completed(Integer result, ByteBuffer attachment) {
		attachment.flip();
		byte[] body = new byte[attachment.remaining()];
		attachment.get(body);
		try {
			String req = new String(body, "UTF-8");
			System.out.println("收到的消息：" + req);
			String currentime = "TIME".equals(req) ? System.currentTimeMillis() + "" : "ERROR";
			doWrite(currentime);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}

	private void doWrite(String currentime) {
		if (currentime != null && currentime.trim().length() > 0) {
			byte[] bytes = currentime.getBytes();
			ByteBuffer byteBuffer = ByteBuffer.allocate(bytes.length);
			byteBuffer.put(bytes);
			byteBuffer.flip();
			asynchronousSocketChannel.write(byteBuffer, byteBuffer, new CompletionHandler<Integer, ByteBuffer>() {

				@Override
				public void completed(Integer result, ByteBuffer attachment) {
					if (byteBuffer.hasRemaining()) {
						asynchronousSocketChannel.write(byteBuffer, attachment, this);
					}
				}

				@Override
				public void failed(Throwable exc, ByteBuffer attachment) {
					try {
						asynchronousSocketChannel.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			});
		}
	}

	@Override
	public void failed(Throwable exc, ByteBuffer attachment) {
		try {
			this.asynchronousSocketChannel.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
